<template>
  <div v-loading="pageLoading">
    <div class="gl_mb_20 demo-input-suffix gl_searchBox">
      <el-row :gutter="20">
        <el-col :span="4">
          <p>考试科目</p>
          <el-select v-model="qo.SubjectId" size="mini" placeholder="请选择考试科目" @change="getPageList()">
            <el-option v-for="item in examSubjects" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <p>查询搜索</p>
          <el-input v-model.trim="qo.Name" placeholder="请输入姓名进行查询" size="mini" clearable @change="getPageList()" />
        </el-col>
        <el-col :span="16" style="text-align:right">
          <el-button style="margin-top:27px" type="primary" size="mini" @click="getPageList()">查询</el-button>
          <el-button style="margin-top:27px" type="warning" size="mini" @click="resetQO">重置</el-button>
        </el-col>
      </el-row>
    </div>

    <div class="mb_8">
      <el-button type="primary" size="medium" @click="clickBatch">批量审核</el-button>
    </div>

    <el-table v-loading="tableLoading" size="mini" :data="tableData" class="gl_table_noBorder mb_17" style="width: 100%" @selection-change="selectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column type="index" label="序号" width="55" />
      <el-table-column label="姓名" width="240">
        <template slot-scope="{ row }">
          <div class="gl_clear">
            <div class="gl_mr_10 gl_fl">
              <img class="table_photo" :src="getStaticFileUrl(row.registerImagePath)" alt="">
              <!-- <img class="player_photo" :src="getStaticFileUrl(row.registerImagePath)" @error="errorPhoto"> -->
            </div>
            <div class="table_name gl_fl">
              <div>{{ row.registerName }}</div>
              <div>{{ row.idCardNumber }}</div>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column width="45">
        <template slot-scope="{ row }">
          <div v-if="row.isOfficial" class="flex_official">官</div>
        </template>
      </el-table-column>
      <el-table-column prop="subjectName" label="科目" />
      <el-table-column prop="certificateName" label="证书名称" />
      <el-table-column prop="certificateLevelName" label="证书等级" width="140" />
      <el-table-column prop="certificateNumber" label="证书编号" />

      <el-table-column width="140" label="成绩">
        <template slot-scope="{ row }">
          <span v-if="!row.isEdit">{{ row.score ? row.score : '' }}</span>
          <el-input v-else v-model.trim="row.inputScore" size="mini" />
        </template>
      </el-table-column>
      <el-table-column width="160" label="考试官">
        <template slot-scope="{ row }">
          <span v-if="!row.isEdit">{{ row.examinerName }}</span>
          <el-select v-else v-model="row.inputExaminerId" size="mini" placeholder="请选择考试官">
            <el-option v-for="item in examinersFilterBySubjectId" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column width="140" label="审核">
        <template slot-scope="{ row }">
          <span v-if="!row.isEdit">{{ row.approveStatusName }}</span>
          <el-select v-else v-model="row.inputApproveStatusCode" size="mini" placeholder="请选择审核结果">
            <el-option v-for="(item, index) in dict.entryScoreApproveStatus" :key="index" :label="item.value" :value="item.code" />
          </el-select>
        </template>
      </el-table-column>

      <el-table-column width="180" label="操作">
        <template slot-scope="{ row }">
          <el-button v-if="!row.isEdit" size="mini" type="text" @click="clickEidt(row)">审核</el-button>
          <el-button v-if="row.isEdit" size="mini" type="text" @click="clickComplete(row)">完成</el-button>
          <el-button v-if="row.isEdit" size="mini" type="text" @click="clickCancel(row)"><span class="gl_color_error">取消</span></el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      title="调整审查状态"
      :visible.sync="dialogVisible"
      width="420px"
      class="gl_dialog_TitleLine gl_dl_footer"
    >
      <el-form ref="form" class="gl_form_mini" size="medium" label-position="top" label-width="80px">
        <el-form-item label="审查状态">
          <el-select v-model="batchStatus" placeholder="请选择" style="width:100%">
            <el-option v-for="(item, index) in dict.entryScoreApproveStatus" :key="index" :label="item.value" :value="item.code" />
          </el-select>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button size="medium" @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" size="medium" @click="submitBatch">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 分页 -->
    <el-row style="text-align: right;">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="qo.MaxResultCount"
        :current-page="qo.Page"
        @size-change="changePageSize"
        @current-change="changePage"
      />
    </el-row>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';

import {
  api_GET_TrainSubject, // 获取科目列表
  api_GET_TrainExaminerExaminersTrainningId, // 分页获取考官人员列表
  api_POST_TrainExaminerScoreBactApprovaScore, // 批量审核成绩（后台）
  api_GET_TrainExaminerScoreSubjectRegisterScores, // 获取培训科目下人员的成绩（后台）
  api_POST_TrainExaminerScoreReisterSubjectScoreSubjectEntryId, // 添加成绩（C端/后台）
  api_PUT_TrainExaminerScoreReisterSubjectScoreSubjectEntryScoreId // 修改成绩（C端/后台）
} from '@/extend/api/trainswaggerApi/app.js';

import {
  Api_GET_TrainExaminerScoreSubjectRegisterScoresQO
} from '@/lib/form/train/swaggerForm.js';

export default {
  data () {
    return {
      qo: new Api_GET_TrainExaminerScoreSubjectRegisterScoresQO(),
      total: 0,
      trainId: '',
      examSubjects: [],
      pageLoading: false,
      tableData: [],
      examiners: [],
      selectData: [],
      dialogVisible: false,
      batchStatus: '',
      tableLoading: false,
      currentSubjectId: ''
    };
  },
  computed: {
    ...mapState({
      dict: state => state.dict.dict
    }),
    examinersFilterBySubjectId () {
      const _this = this;
      return _this.examiners.filter(item => {
        return item.examinerSubjects.some(jtem => jtem.subjectId === _this.currentSubjectId);
      });
    }
  },
  created() {
    this.getDict();
    this.trainId = this.$route.params.id;
    this.qo.TrainningId = this.trainId;
    this.getPageList(); // 不传subjectId
    this.getSubject({
      TrainningId: this.trainId
    });
    this.getExamer();
  },
  methods: {
    ...mapActions({ getDict: 'dict/getDict' }),
    // 获取下拉
    getSubject (qo) {
      this.pageLoading = true;
      api_GET_TrainSubject(qo)
        .then(
          res => {
            this.pageLoading = false;
            this.examSubjects = res.examSubjects || [];
            this.examSubjects.forEach(item => {
              if (item.isOfficial) {
                item._name = item.name;
                item.name = `${item.name}（官）`;
              }
            });
            this.examSubjects.unshift({
              name: '全部',
              id: null
            });
            this.qo.SubjectId = this.examSubjects[0] ? this.examSubjects[0].id : '';
            // this.getPageList(); // 必传subjectId
          }
        )
        .catch(
          error => {
            this.pageLoading = false;
            this.$message({
              message: `科目获取失败 ${error.error.message}`,
              type: 'error',
              showClose: true
            });
          }
        );
    },
    // 获取考试官
    getExamer () {
      this.tableLoading = true;
      api_GET_TrainExaminerExaminersTrainningId(this.trainId, {
        IncludeTrainning: false
      })
        .then(
          res => {
            this.tableLoading = false;
            this.examiners = res.items || [];
          }
        )
        .catch(
          error => {
            this.tableLoading = false;
            this.$message({
              type: 'error',
              showClose: true,
              message: `考试官表获取失败 ${error.error.message}`
            });
          }
        );
    },
    getPageList (page) {
      // if (!this.qo.SubjectId) {
      //   console.log('Missing SubjectId');
      //   return;
      // }
      this.tableLoading = true;
      const _qo = JSON.parse(JSON.stringify(this.qo));
      _qo.Page = page || 1;
      _qo.SkipCount = (_qo.Page - 1) * _qo.MaxResultCount;
      api_GET_TrainExaminerScoreSubjectRegisterScores(_qo)
        .then(
          res => {
            this.tableLoading = false;
            const _list = res.items || [];
            this.tableData = _list.map(item => {
              item.isEdit = false;
              item.inputApproveStatusCode = ''; // 审核状态Code
              item.inputExaminerId = ''; // 考试官ID
              item.inputScore = ''; // 成绩
              return item;
            });
            this.total = res.totalCount;
          }
        )
        .catch(
          error => {
            this.tableLoading = false;
            this.$message({
              type: 'error',
              showClose: true,
              message: `成绩列表获取失败 ${error.error.message}`
            });
          }
        );
    },
    resetQO () {
      const qo = new Api_GET_TrainExaminerScoreSubjectRegisterScoresQO();
      qo.SubjectId = this.examSubjects[0] ? this.examSubjects[0].id : '';
      qo.TrainningId = this.trainId;
      this.qo = qo;
    },
    selectionChange (val) {
      this.selectData = val;
    },
    // 批量审核
    clickBatch() {
      if (!this.selectData.length) {
        this.$message({
          type: 'warning',
          showClose: true,
          message: `请先勾选要审核的人员`
        });
        return;
      }
      this.dialogVisible = true;
    },
    // 确认审核
    submitBatch() {
      if (!this.batchStatus) {
        this.$message({
          type: 'warning',
          showClose: true,
          message: `请选择审查状态`
        });
        return;
      }
      const _vo = {
        approveStatusCode: this.batchStatus,
        subjectEntryScoreIds: this.selectData.map(item => {
          return {
            subjectEntryScoreId: item.subjectEntryScoreId,
            subjectEntryId: item.subjectEntryId
          };
        })
      };
      this.batchAPI(_vo);
    },
    batchAPI (vo) {
      this.tableLoading = true;
      api_POST_TrainExaminerScoreBactApprovaScore(vo)
        .then(
          res => {
            this.tableLoading = false;
            if (res) {
              this.batchStatus = '';
              this.dialogVisible = false;
              this.getPageList();
              this.$message({
                type: 'success',
                showClose: true,
                message: `批量审核成功！`
              });
            } else {
              this.$message({
                type: 'error',
                showClose: true,
                message: `批量审核失败！`
              });
            }
          }
        )
        .catch(
          error => {
            this.tableLoading = false;
            this.$message({
              type: 'error',
              showClose: true,
              message: `批量审核失败 ${error.error.message}`
            });
          }
        );
    },

    clickEidt (row) {
      this.currentSubjectId = row.subjectId;
      row.isEdit = true;
      row.inputApproveStatusCode = row.approveStatusCode; // 审核状态Code
      row.inputExaminerId = row.examinerId; // 考试官ID
      row.inputScore = row.score; // 成绩

      console.log('row: ', row);
    },
    clickComplete (row) {
      if (!row.inputApproveStatusCode) {
        this.$message({
          type: 'warning',
          showClose: true,
          message: `请选择审核状态`
        });
        return;
      }
      this.tableLoading = true;
      const _vo = {
        // registerId: row.registerId, // B端不需要此字段
        examinerId: row.inputExaminerId || null,
        score: row.inputScore,
        approveStatusCode: row.inputApproveStatusCode
      };
      if (row.subjectEntryScoreId) {
        this.editReuslt(row.subjectEntryScoreId, _vo, row);
      } else {
        this.addResult(row.subjectEntryId, _vo, row);
      }
    },
    editReuslt(subjectEntryScoreId, vo, row) {
      api_PUT_TrainExaminerScoreReisterSubjectScoreSubjectEntryScoreId(subjectEntryScoreId, vo)
        .then(
          () => {
            row.isEdit = false;
            this.getPageList(this.qo.Page);
          }
        )
        .catch(
          error => {
            this.tableLoading = false;
            this.$message({
              type: 'error',
              showClose: true,
              message: `修改失败 ${error.error.message}`
            });
          }
        );
    },
    addResult(subjectEntryId, vo, row) {
      api_POST_TrainExaminerScoreReisterSubjectScoreSubjectEntryId(subjectEntryId, vo)
        .then(
          () => {
            row.isEdit = false;
            this.getPageList(this.qo.Page);
          }
        )
        .catch(
          error => {
            this.tableLoading = false;
            this.$message({
              type: 'error',
              showClose: true,
              message: `修改失败 ${error.error.message}`
            });
          }
        );
    },
    clickCancel (row) {
      row.isEdit = false;
      row.inputValue = row.name;
    },
    getStaticFileUrl(relativeUrl) {
      if (!relativeUrl) return '';
      return WEB_CONFIG.VUE_APP_STATIC_FILE_RUL + relativeUrl;
    },
    // 分页
    changePage(page) {
      this.getPageList(page);
    },
    changePageSize(pagesize) {
      this.qo.MaxResultCount = pagesize;
      this.getPageList();
    }
  }
};
</script>

<style lang="scss" scoped>
  .table_photo {
    width: 36px;
    height: 36px;
    border-radius: 50%;
  }
  .table_name {
    line-height: 18px;
  }
  .mb_8 {
    margin-bottom: 8px;
  }
  .mb_17 {
    margin-bottom: 17px;
  }
  .dialog-footer {
    text-align: center;
  }

  .flex_official {
    box-sizing: border-box;
    width: 22px;
    height: 22px;
    font-size: 12px;
    line-height: 22px;
    text-align: center;
    color: #1990ff;
    border: 1px solid #1990ff;
    border-radius: 50%;
    background-color: #fff;
  }
</style>
